package com.lwf.smartseniorcare.controller;

import com.lwf.smartseniorcare.dto.ElderlyDTO;
import com.lwf.smartseniorcare.service.ElderlyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/elderly")
public class ElderlyController {

    @Autowired
    ElderlyService elderlyService;

    // Get all elderly - accessible to all authenticated users
    @GetMapping
    public ResponseEntity<List<ElderlyDTO>> getAllElderly() {
        List<ElderlyDTO> elderlyList = elderlyService.getAllElderly();
        return ResponseEntity.ok(elderlyList);
    }

    // Get elderly by ID - accessible to all authenticated users
    @GetMapping("/{id}")
    public ResponseEntity<ElderlyDTO> getElderlyById(@PathVariable Long id) {
        ElderlyDTO elderly = elderlyService.getElderlyById(id);
        return ResponseEntity.ok(elderly);
    }

    // Create elderly - only accessible to ADMIN and DOCTOR
    @PreAuthorize("hasRole('ADMIN') or hasRole('DOCTOR')")
    @PostMapping
    public ResponseEntity<ElderlyDTO> createElderly(@RequestBody ElderlyDTO elderlyDTO) {
        ElderlyDTO createdElderly = elderlyService.createElderly(elderlyDTO);
        return ResponseEntity.ok(createdElderly);
    }

    // Update elderly - only accessible to ADMIN and DOCTOR
    @PreAuthorize("hasRole('ADMIN') or hasRole('DOCTOR')")
    @PutMapping("/{id}")
    public ResponseEntity<ElderlyDTO> updateElderly(@PathVariable Long id, @RequestBody ElderlyDTO elderlyDTO) {
        ElderlyDTO updatedElderly = elderlyService.updateElderly(id, elderlyDTO);
        return ResponseEntity.ok(updatedElderly);
    }

    // Delete elderly - only accessible to ADMIN
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteElderly(@PathVariable Long id) {
        elderlyService.deleteElderly(id);
        return ResponseEntity.ok("Elderly deleted successfully");
    }

    // Get elderly by caretaker
    @GetMapping("/caretaker/{caretakerId}")
    public ResponseEntity<List<ElderlyDTO>> getElderlyByCaretaker(@PathVariable Long caretakerId) {
        List<ElderlyDTO> elderlyList = elderlyService.getElderlyByCaretaker(caretakerId);
        return ResponseEntity.ok(elderlyList);
    }

    // Search elderly by name
    @GetMapping("/search/{name}")
    public ResponseEntity<List<ElderlyDTO>> searchElderlyByName(@PathVariable String name) {
        List<ElderlyDTO> elderlyList = elderlyService.searchElderlyByName(name);
        return ResponseEntity.ok(elderlyList);
    }
}
